package com.preparation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.preparation.domain.Post;
import com.preparation.domain.Collection;
import com.preparation.mapper.CollectionMapper;
import com.preparation.mapper.PostMapper;
import com.preparation.service.ICollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements ICollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private PostMapper postMapper;

    //收藏  取消收藏
    @Override
    public Boolean collect(Collection collection){
        if(collectionMapper.deleteByUidPid(collection) > 0){
            //如果找到收藏信息，并删除，则帖子收藏数-1
            return postMapper.updateCollectsCount(collection.getPostId(), -1) > 0;
        }else{
            //如果未找到收藏信息，则新增收藏信息，帖子收藏数+1
            boolean flag = collectionMapper.insert(collection) > 0;
            if (flag){
                return postMapper.updateCollectsCount(collection.getPostId(), 1) > 0;
            }else{
                collectionMapper.deleteByUidPid(collection);
            }
        }
        return false;
    }

    //根据用户id和帖子id查询用户是否收藏
    @Override
    public Boolean getByUidPid(Collection collection){
        return collectionMapper.getByUidPid(collection) > 0;
    }

    //获取用户收藏的列表
    @Override
    public List<Post> getByUid(Integer userId) {
        List<Integer> idList = collectionMapper.getByUid(userId);
        LambdaQueryWrapper<Post> qw = new LambdaQueryWrapper<>();
        if (idList.size()>0){
            qw.in(Post::getId, idList);
        }else{
            return null;
        }
        return postMapper.selectList(qw);
    }

}
